<template>
  <div class="table-box">
    <div class="table-search">
      <div class="btn-box">
        <el-button type="primary" plain @click="onAdd">添加权限组</el-button>
        <el-button type="primary" plain @click="onExport">导出</el-button>
      </div>
    </div>
    <div class="card content-box">
      <div class="table">
        <el-table :data="tableData" border v-loading="loading">
          <el-table-column prop="id" label="组ID" align="center" />
          <el-table-column prop="name" label="组名称" align="center" />
          <el-table-column
            prop="project_name"
            label="项目名称"
            align="center"
          />
          <el-table-column
            prop="project_code"
            label="项目code"
            align="center"
          />
          <el-table-column label="操作" align="center" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                plain
                @click="handleEdite(scope.$index, scope.row)"
                >编辑</el-button
              >
              <el-button
                type="primary"
                plain
                @click="handleSettings(scope.$index, scope.row)"
                >设置权限</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-dialog
      v-model="dialogFormVisible"
      :destroy-on-close="true"
      title="权限组信息"
      width="450px"
      @close="closeDialog"
    >
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="rules">
        <el-form-item label="组名称" :label-width="formLabelWidth" prop="name">
          <el-input v-model="dialogForm.name" />
        </el-form-item>
        <el-form-item
          label="项目名称"
          :label-width="formLabelWidth"
          prop="project_name"
        >
          <el-select v-model="dialogForm.project_name" placeholder="请选择">
            <el-option
              v-for="item in projectOptions"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="项目代码" :label-width="formLabelWidth" prop="project_code">
          <el-select v-model="dialogForm.project_code" placeholder="请选择">
            <el-option v-for="item in projectOptions" :key="item.code" :label="item.name" :value="item.code"> </el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item label="id" style="display: none">
          <el-input v-model="dialogForm.id" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="submit" :loading="btnLoading">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 权限 -->
    <el-drawer v-model="drawer" direction="rtl" size="60%" @close="closeDrawer">
      <template #header="{ close, titleId, titleClass }">
        <h3 :id="titleId" :class="titleClass">配置组权限</h3>
        <div class="mr-30">
          <el-button type="primary" @click="savePermission"
            >保存权限
          </el-button>
        </div>
      </template>
      <div class="permission-box">
        <template v-for="item in allPermissions" :key="item.project_name">
          <div class="flex">
            <span>项目:</span
            ><span class="ml-20" style="font-weight: 700">{{
              item.project_name
            }}</span>
          </div>
          <div>
            <span>菜单:</span>
            <el-checkbox-group v-model="checkedData">
              <TreeCheckbox
                :permissions="item.permissions"
                @selectCheckbox="selectCheckbox"
              />
            </el-checkbox-group>
          </div>
        </template>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import TreeCheckbox from "@/components/TreeCheckbox/index.vue";
import { exportToExcel } from "@/utils/utils";
import {
  addGroupApi,
  groupApi,
  editeGroupApi,
  permissionAllApi,
  editeGroupPermissionApi,
  groupPermissionApi,
  projectApi,
} from "@/api/system/system";

const loading = ref(false);
const btnLoading = ref(false);
const dialogFormRef = ref(null);
const drawer = ref(null);
const formLabelWidth = "120px";
const dialogFormVisible = ref(false);
const type = ref(null);
const tableData = ref([]);
const checkedData = ref([]); //选中数据

const permissions = ref([]); //设置发送后端的权限组数据

const rowId = ref(null);
const projectOptions = ref([]);

//权限菜单数据
const allPermissions = ref([
  // {
  //   project_name: "GMeta",
  //   project_code: "gmeta",
  //   permissions: [
  //     {
  //       children: [
  //         {
  //           code: "mainnet",
  //           name: "主链管理",
  //           parentId: "wallet",
  //           method: [
  //             {
  //               code: "mainnet-add",
  //               name: "添加",
  //               parentId: "mainnet",
  //             },
  //             {
  //               code: "mainnet-delete",
  //               name: "删除",
  //               parentId: "mainnet",
  //             },
  //           ],
  //         },
  //       ],
  //       code: "wallet",
  //       name: "钱包管理",
  //       parentId: 0,
  //     },
  //   ],
  // },
]);
// 权限树
const treeMap = new Map();
// treeMap.set("wallet", {
//   children: [
//     {
//       code: "mainnet",
//       name: "主链管理",
//       parentId: "wallet",
//       method: [
//         {
//           code: "mainnet-add",
//           name: "添加",
//           parentId: "mainnet",
//         },
//         {
//           code: "mainnet-delete",
//           name: "删除",
//           parentId: "mainnet",
//         },
//       ],
//     },
//   ],
//   code: "wallet",
//   name: "钱包管理",
//   parentId: 0,
// });

const dialogFormData = {
  id: "",
  name: "",
  project_name: "",
  project_code: "",
};
const dialogForm = reactive({ ...dialogFormData });

// 参数
const param = () => {
  return {};
};

// 入参project_name
const getProjectCode = (project_name) => {
  let code = "";
  projectOptions.value.map((item) => {
    console.log(item.name, project_name);
    if (item.name == project_name) {
      code = item.code;
    }
  });
  console.log("----", code);
  return code;
};

// 获取表格数据
const getTbaleList = async () => {
  try {
    const res = await projectApi(param());
    projectOptions.value = res.data;
  } catch (error) {
    console.log(error);
  }
};
// 校验
const rules = {
  name: [{ required: true, message: "请输入组名称", trigger: "blur" }],
  project_name: [
    { required: true, message: "请输入项目名称", trigger: "blur" },
  ],
  // project_code: [{ required: true, message: '请输入项目代码', trigger: 'blur' }],
};

// 格式化权限菜单数据
const formatPermissionData = (data) => {
  const arr = [];
  data.map((item) => {
    let obj = {
      project_name: item.project_name,
      project_code: item.project_code,
      permissions: [],
    };
    if (item.permissions.length > 0) {
      item.permissions.map((childrenItem) => {
        let children = {
          code: childrenItem.code,
          name: childrenItem.name,
          parentId: 0,
          method: [],
        };
        // 操作方法
        if (childrenItem.method && childrenItem.method.length > 0) {
          childrenItem.method.map((methodItem) => {
            let method = {
              code: childrenItem.code + methodItem.method,
              name: methodItem.name,
              parentId: childrenItem.code,
              code_name: methodItem.method,
            };
            children.method.push(method);
          });
        }
        obj.permissions.push(children);
      });
    }
    arr.push(obj);
  });

  return arr;
};
// 设置权限树
const formatPermissiontreeMap = (data) => {
  data.map((item) => {
    if (item.permissions && item.permissions.length > 0) {
      item.permissions.map((children) => {
        treeMap.set(children["code"], children);
      });
    }
  });
};

// 获取表格数据
const getTbaleData = async () => {
  loading.value = true;
  try {
    const res = await groupApi(param());
    loading.value = false;
    tableData.value = res.data;
  } catch (error) {
    loading.value = false;
  }
};
//获取全部权限

const getPermissionAll = async () => {
  try {
    const res = await permissionAllApi();
    allPermissions.value = formatPermissionData(res.data.all_permissions);
    formatPermissiontreeMap(allPermissions.value);
  } catch (error) {
    console.log(error);
  }
};

// 导出
const onExport = async () => {
  const data = Object.assign(param(), { export: 1 });
  const res = await groupApi(data);

  let head = {
    id: "组ID",
    name: "组名称",
    project_name: "项目名称",
    project_code: "项目code",
  };
  exportToExcel(res.data, head, "权限组列表");
};

// 新增
const onAdd = () => {
  dialogFormVisible.value = true;
  type.value = "add";
};
//关闭弹窗
const closeDialog = () => {
  Object.assign(dialogForm, dialogFormData);
  type.value = null;
};

// 取消
const cancel = () => {
  dialogFormVisible.value = false;
  Object.assign(dialogForm, dialogFormData);
  type.value = null;
};

// 提交
const submit = () => {
  dialogFormRef.value
    .validate()
    .then(async () => {
      try {
        btnLoading.value = true;

        dialogForm.project_code = dialogForm.project_name;
        // console.log(dialogForm)
        //新增
        if (type.value == "add") {
          const res = await addGroupApi(dialogForm);
          ElMessage({
            message: res.message,
            type: "success",
          });
        }
        //编辑
        if (type.value == "edite") {
          const res = await editeGroupApi(dialogForm.id, dialogForm);
          ElMessage({
            message: res.message,
            type: "success",
          });
        }
        dialogFormVisible.value = false;
        btnLoading.value = false;
        getTbaleData();
      } catch (error) {
        btnLoading.value = false;
        dialogFormVisible.value = false;
      }
    })
    .catch((error) => {
      console.log(error);
    });
};
//编辑
const handleEdite = (index, row) => {
  Object.assign(dialogForm, { ...row });
  dialogFormVisible.value = true;
  type.value = "edite";
};
//设置组权限
const handleSettings = async (index, row) => {
  drawer.value = true;
  rowId.value = row.id;
  const res = await groupPermissionApi(row.id);
  setSelectCheckbox(res.data.permissions);
  console.log(res);
};

// 设置选中的权限
const setSelectCheckbox = (data) => {
  const checkedDataArr = [];
  const permissionsArr = [];
  data.map((item) => {
    checkedDataArr.push(item.code);
    if (item.method && item.method.length > 0) {
      item.method.map((methodIem) => {
        checkedDataArr.push(item.code + methodIem.method);
        permissionsArr.push({
          code: item.code + methodIem.method,
          name: methodIem.name,
          parentId: item.code,
          code_name: methodIem.method,
        });
      });
    }
  });

  permissions.value = permissionsArr;

  checkedData.value = checkedDataArr;
};

// 关闭设置组权限
const closeDrawer = () => {
  drawer.value = false;
  checkedData.value = [];
  permissions.value = [];
  rowId.value = null;
};
// 选中
const selectCheckbox = (item) => {
  const arr = Object.assign(checkedData.value, []);
  let findIndex = arr.indexOf(item.code);
  if (findIndex == -1) {
    deleteCheckedDataAndChildren(item);
  } else {
    addCheckedDataAndChildren(item);
    selectUpperLevel(item);
  }
};
// 选中
const addCheckedData = (data) => {
  const arr = Object.assign(checkedData.value, []);
  arr.push(data.code);
  checkedData.value = arr;
};
// 选中本级及子级
const addCheckedDataAndChildren = (data) => {
  permissions.value.push(data);
  const arr = Object.assign(checkedData.value, []);
  let findIndex = arr.findIndex((val) => val == data.code);
  // 自己本身
  if (data.code && findIndex == -1) {
    addCheckedData(data);
  }
  // 子节点
  if (data.children) {
    data.children.forEach((item) => {
      addCheckedDataAndChildren(item);
    });
  }
  // 操作方法
  if (data.method) {
    data.method.forEach((item) => {
      addCheckedDataAndChildren(item);
    });
  }
};
//选中上一级
const selectUpperLevel = (data) => {
  const arr = Object.assign(checkedData.value, []);
  // 拿到上级key
  let parentId = data.parentId;
  if (!parentId) {
    return;
  }
  // 从权限树对象 获取该父级对象
  let parentModule = treeMap.get(parentId);

  if (!parentModule) {
    return;
  }
  // 选中父级
  let parentIndex = arr.findIndex((e) => parentModule?.code === e);
  if (parentModule.code && parentIndex == -1) {
    addCheckedData(parentModule);
  }
  // 如果上级还有上级 则进行递归
  if (parentModule.parentId) {
    selectUpperLevel(parentModule);
  }
};

// 取消选中
const deleteCheckedData = (index) => {
  const arr = Object.assign(checkedData.value, []);
  arr.splice(index, 1);
  checkedData.value = arr;
};
// 取消选中本级以及子级
const deleteCheckedDataAndChildren = (data) => {
  // console.log("===>>删除", data);
  const newArray = [];
  permissions.value.filter((item) => {
    if (item.code != data.code) {
      newArray.push(item);
    }
  });
  permissions.value = newArray;
  const arr = Object.assign(checkedData.value, []);
  // 取消选中本级以及子级

  let findIndex = arr.findIndex((val) => val == data.code);

  if (findIndex != -1) {
    deleteCheckedData(findIndex, data);
  }
  if (data.children) {
    data.children.forEach((item) => {
      deleteCheckedDataAndChildren(item);
    });
  }
  if (data.method) {
    data.method.forEach((item) => {
      deleteCheckedDataAndChildren(item);
    });
  }
};

// 设置保存权限数据格式
// {
//   'mainnet':['add','delete']
// }
const setSavePermissionData = (permissions) => {
  const arr = [];
  const obj = {};
  // console.log(permissions)
  permissions.map((item) => {
    if (item.parentId != 0 && !item.method) {
      if (!obj[item.parentId]) {
        obj[item.parentId] = [];
        obj[item.parentId].push(item.code_name);
      } else {
        obj[item.parentId].push(item.code_name);
      }
    }
  });
  for (let item in obj) {
    let method = obj[item];
    arr.push({ code: item, method: method.join(",") });
  }
  // console.log('permissions',arr)
  return arr;
};
// 保存权限
const savePermission = async () => {
  if (!permissions.value.length) {
    ElMessage({
      message: "还未选择任何权限",
      type: "error",
    });
  }
  if (rowId.value) {
    const arr = setSavePermissionData(permissions.value);
    const res = await editeGroupPermissionApi(rowId.value, {
      permissions: arr,
    });
    ElMessage({
      message: res.message,
      type: "success",
    });
  }

  drawer.value = false;
};

onMounted(() => {
  getTbaleData();
  getPermissionAll();
  getTbaleList();
});
</script>

<style>
.el-drawer__header {
  border-bottom: 1px solid #72767b;
  padding: var(--el-drawer-padding-primary);
}
.el-drawer__title {
  color: #000;
  font-size: 20px;
}
</style>
